package com.sen.gulimall.sso.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Kisen
 * @email lqs0911@qq.com
 * @date 2022/11/5 16:03
 * @detail
 */
@Controller
public class HelloController {

    @Value("${sso.server}")
    private String ssoServerUrl;

    @Value("${sso.client}")
    private String ssoClientUrl;

    /**
     * 无需登录就可以访问
     *
     * @return
     */
    @ResponseBody
    @GetMapping("hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("employees")
    public String employees(Model model, HttpSession session,
                            @RequestParam(value = "token", required = false) String token) {
        if (!StringUtils.isEmpty(token)){
            //去ssoserver登录成功回来就会带上token
            //去ssoserver获取当前token真正对应的用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity(ssoServerUrl + "/userInfo?token=" + token, String.class);
            session.setAttribute("loginUser", forEntity.getBody());
        }

        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            //没登录，跳转到登陆服务器进行登录
            //跳转过去以后，使用url上的查询参数标识我们自己是哪个页面
            return "redirect:" + ssoServerUrl + "/login.html?redirect_url=" + ssoClientUrl + "/employees";
        }

        List<String> emps = new ArrayList<>();
        emps.add("张三");
        emps.add("李四");
        model.addAttribute("emps", emps);
        return "employees";
    }
}
